import {cacheKey, commonConstant} from '@/common/constant.js';
import {isNotEmpty,isEmpty} from "@/utils/utils";
import { memberInfo,checkToken } from '@/common/http.api.js';
//===============缓存方法的定义===============
// 获取token
const getAccessToken = function () {
    let token = '';
    try {
		token = uni.getStorageSync(cacheKey.TOKEN) || "";
    } catch (e) {}
    return token;
}
// 设置token
const setAccessToken = (access_token) => {
    try {
        uni.setStorageSync(cacheKey.TOKEN, access_token);
        return true;
    } catch (e) {
        return false;
    }
}
//清除token
const clearAccessToken = function () {
    try {
        uni.removeStorageSync(cacheKey.TOKEN);
    } catch (e) {
    }
}
//设置userinfo
const setUserInfo = (user) => {
    try {
        uni.setStorageSync(cacheKey.MEMBER_INFO, user);
        return true;
    } catch (e) {
        return false;
    }
}
//获取userinfo
const getUserInfo = function () {
    try {
        return uni.getStorageSync(cacheKey.MEMBER_INFO) || {
            avatar: commonConstant.avatar
        };
        //return uni.getStorageSync(cacheKey.MEMBER_INFO);
    } catch (e) {
        return false;
    }
}

//获取userinfo
const getUserId = function () {
    try {
        return uni.getStorageSync(cacheKey.MEMBER_INFO) ? uni.getStorageSync(cacheKey.MEMBER_INFO).id : 0;
        //return uni.getStorageSync(cacheKey.MEMBER_INFO);
    } catch (e) {
        return false;
    }
}

//清除userinfo
const clearMemberInfo = function () {
    try {
        uni.removeStorageSync(cacheKey.MEMBER_INFO)
    } catch (e) {
    }
}

const getLogin = function () {
    try {
        return uni.getStorageSync(cacheKey.IS_LOGIN) || false;
    } catch (e) {
        return false;
    }
}

const setLogin = function (data) {
    try {
        uni.setStorageSync(cacheKey.IS_LOGIN, data)
    } catch (e) {
    }
}

const clearLogin = function () {
    try {
        uni.removeStorageSync(cacheKey.IS_LOGIN)
    } catch (e) {
    }
}

//验证是否需要登陆
const verifyLogin = function (){
    var flag = getLogin();
    if(!flag){
        uni.redirectTo({
            url: "pages/common/public/login_one"
        });
    }
}

//刷新用户信息
function refreshMemberInfo() {
    memberInfo().then((res)=>{
        setUserInfo(res.data);
    }).catch(err=>{
        console.error(err)
    })
}

//校验token是否有效
function checkTokenValid() {
    let flag = false;
    const token = getAccessToken();
    checkToken(token).then(res => {
        if(res.code === 0){
            flag = true;
        }else {
            setAccessToken(null);
        }
    }).catch(err => {
        setAccessToken(null);
    })
    return flag;
}

//退出登陆
function logout(){
    clearAccessToken();
    clearMemberInfo();
	clearLogin();
}



export default {
    getAccessToken,
    setAccessToken,
    clearAccessToken,
    getUserInfo,
    setUserInfo,
	getUserId,
    clearMemberInfo,
    verifyLogin,
    checkTokenValid,
    refreshMemberInfo,
    logout,
    getLogin,
    clearLogin,
    setLogin
}
